<?php
	include_once("dbcon.php");
	
	$instance = new DbConnection("localhost","root","warehause");
	
	if (!isset($_SESSION['id']))
{
	// check cookies
	if (isset($_COOKIE['login']) && isset($_COOKIE['password']))
	{
		// trying to authorize using existing credentials
		$login = mysql_escape_string($_COOKIE['login']);
		$password = mysql_escape_string($_COOKIE['password']);

		// trying to find user by login and password
		$query = "SELECT `id`
					FROM `users`
					WHERE `login`='{$login}' AND `password`='{$password}'
					LIMIT 1";
		$sql = mysql_query($query) or die(mysql_error());

		// found
		if (mysql_num_rows($sql) == 1)
		{
			// mark in session state (put user id)
			$row = mysql_fetch_assoc($sql);
			$_SESSION['user_id'] = $row['id'];

			// BE CARE! DON'T FORGET TO PUT session_start(); TO EACH YOUR PAGE
		}
	}
	else {
		$query = "SELECT * FROM users";
		$sql = mysql_query($query);
		if(mysql_num_rows($sql)<=0) {
			$login = "admin";
			$password = "admin";
			$salt = '666';
			$hashed_password = md5(md5($password) . $salt);
			// Create sensei
			$query = "INSERT INTO users VALUES(NULL,'{$login}','{$login}','{$login}',1,'{$login}','{$hashed_password}','{$salt}');";
			mysql_query($query);
			
			// Create sensei role
			$query = "INSERT INTO roles VALUES(NULL,'Administrator',4,4,4,4);";
			mysql_query($query);
		}
	}
}
?>